﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.IdentityModel.Protocols.WSFederation;

namespace Veracruz.Facebook.Web
{
    public sealed class FacebookLoginHandler : IHttpHandler
    {
        #region consts

        //private const string FacebookLoginUrl = "http://www.facebook.com/login.php?api_key={0}&v={1}&next={2}";
        //private const string FacebookLoginUrl = "http://api.new.facebook.com/login.php?api_key={0}&auth_token={1}&callback_url=www.google.com&v=1.0&popup";
        private const string FacebookLoginUrl = "http://www.facebook.com/login.php?api_key={0}&v=1.0&popup&next={1}";

        #endregion
        #region ctors

        public FacebookLoginHandler()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        #endregion
        #region methods

        public bool IsReusable
        {
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {
            string l_realm = context.Request[WSFederationConstants.Parameters.Realm];
            string l_action = context.Request[WSFederationConstants.Parameters.Action];
            string l_returnUrl = context.Request[Constants.ReturnUrl];

            l_returnUrl = l_returnUrl.IndexOf("?") > 0 ? l_returnUrl.Substring(0, l_returnUrl.IndexOf("?")) : l_returnUrl;

            string l_next = string.Format("?{0}={1}&{2}={3}&{4}={5}",
                Constants.ReturnUrl, l_returnUrl,
                WSFederationConstants.Parameters.Realm, l_realm, 
                WSFederationConstants.Parameters.Action, l_action);

            //string l_authenticationToken = FacebookHelper.CreateAuthenticationToken();
            //string l_url = string.Format(FacebookLoginUrl, Constants.ApplicationKey, l_authenticationToken, HttpUtility.UrlEncode(l_next));

            string l_url = string.Format(FacebookLoginUrl, Constants.ApplicationKey, HttpUtility.UrlEncode(l_next));
            HttpContext.Current.Response.Redirect(l_url);
        }

        #endregion
    }
}
